package com.macaline.nio;

import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

public class PipDemo {


    @Test
    public void demo1() throws IOException {
        // 1.获取通道
        Pipe pipe = Pipe.open();

        // 2.获取sink通道
        Pipe.SinkChannel sink = pipe.sink();

        // 3.创建缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.put("test".getBytes());
        buffer.flip();

        // 4.写入数据
        sink.write(buffer);

        // 5.获取source通道
        Pipe.SourceChannel source = pipe.source();

        // 6、读取数据
        buffer.flip();
        int read = source.read(buffer);
        System.out.println(new String(buffer.array(), 0, read));


        // 7、关闭通道
        sink.close();
        source.close();
    }

}
